package com.shangting.web.controller.login;


import com.shangting.common.result.Result;
import com.shangting.common.utils.JwtUtil;
import com.shangting.web.service.LoginService;
import com.shangting.web.vo.login.CaptchaVo;
import com.shangting.web.vo.login.LoginVo;
import com.shangting.web.vo.system.user.SystemUserInfoVo;
import com.shangting.web.vo.token.TokenVo;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

@Tag(name = "后台管理系统登录管理")
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("login/captcha")
    public Result<CaptchaVo> getCaptcha() {
        CaptchaVo captcha = loginService.getCaptcha();
        return Result.ok(captcha);
    }

    @Operation(summary = "登录")
    @PostMapping("login")
    public Result<TokenVo> login(@RequestBody LoginVo loginVo) {
        TokenVo tokenVo = loginService.login(loginVo);
        return Result.ok(tokenVo);
    }

    @PostMapping("/refreshToken")
    public Result<?> refresh(@RequestBody String refreshToken) {
        Claims claims = JwtUtil.parseToken(refreshToken);
        if (claims == null || claims.getExpiration().before(new Date())) {
            return Result.fail(401, "refresh token 失效，请重新登录");
        }
        String newAccessToken = JwtUtil.createAccessToken(new Long(String.valueOf(claims.get("userId"))), (String) claims.get("username"));
        String newRefreshToken = JwtUtil.createRefreshToken(new Long(String.valueOf(claims.get("userId"))), (String) claims.get("username"));
        return Result.ok(new TokenVo(newAccessToken, newRefreshToken));
    }

    @Operation(summary = "获取登陆用户个人信息")
    @GetMapping("info")
    public Result<SystemUserInfoVo> info(@RequestHeader("Authorization") String token) {
        Claims claims = JwtUtil.parseToken(token.substring(7));
        Long userId = claims.get("userId", Long.class);
        SystemUserInfoVo userInfo = loginService.getLoginUserInfo(userId);
        return Result.ok(userInfo);
    }
}